package com.sumer.psychology.comment.infrastructure.persistence.hibernate;


import com.sumer.psychology.comment.domain.model.*;
import com.sumer.psychology.common.persistence.hibernate.AbstractHibernateRepository;
import org.hibernate.Query;

import java.util.List;
import java.util.UUID;

/**
 * 评论资源库
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/8/14
 * Time: 15:22
 */
public class HibernateCommentRepository extends AbstractHibernateRepository implements CommentRepository {
    @Override
    public CommentId nextIdentity() {
        return new CommentId(UUID.randomUUID().toString());
    }

    @Override
    public void add(Comment aComment) {
        session().saveOrUpdate(aComment);
    }

    @Override
    public Comment commentOfId(CommentId commentId) {
        Query query = session()
                .createQuery("from Comment where commentId=:commentId and availability=:availability")
                .setParameter("commentId", commentId)
                .setParameter("availability", CommentAvailability.ACTIVE);

        return (Comment) query.uniqueResult();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Comment> commentsOfHost(CommentHost host) {
        Query query = session()
                .createQuery("from Comment where host=:host and availability=:availability")
                .setParameter("host", host)
                .setParameter("availability", CommentAvailability.ACTIVE);
        return query.list();
    }
}
